<?php

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die();
jimport('joomla.application.component.controller');

/**
 * Server Component Controller
 */
class ServerController extends JController
{
    /**
     * Task write order
     */
    function wrord()
    {
        JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR . DS . 'tables');
        $row =& JTable::getInstance('zakaz', 'Table');

        $row->idserver = JRequest::getVar("idserver");
        $row->text = "from register user";

        $user =& JFactory::getUser();

        if ($user->id) {
            $row->iduser = $user->id;
        } else {
            $row->iduser = 0;
        }
        $row->text = "from register user";

        if (!$row->store()) {
            JError::raiseError(500, $row->getError());
        } else {
            $this->wrServerOrder(JRequest::getVar("idserver"));
            $this->SendEmail("Order write to DB. User id=" . $row->iduser . " Code server = " . JRequest::getVar("idserver"));
        }
        $this->setRedirect('index.php?option=com_server&view=complete&cid[]=' . JRequest::getVar("idserver"), 'Спасибо, с Вами свяжутся после оплаты');
    }

    /**
     * Inc count orders for server
     */
    function wrServerOrder($idserver)
    {

        $_db = & JFactory::getDBO();
        $query = ' SELECT * FROM #__server ' .
            '  WHERE id = ' . $idserver;
        $_db->setQuery($query);
        $r = $_db->loadObject();

        $query = "UPDATE #__server "
            . " SET countzakaz = " . (int)($r->countzakaz + 1)
            . " WHERE (id = " . (int)$idserver . ")";

        $_db->setQuery($query);

        if (!$_db->query()) {
            JError::raiseError(500, $this->_db->getErrorMsg());
        }
    }

    /**
     * Send email to admin
     */
    function SendEmail($mess)
    {

        $mailer =& JFactory::getMailer();

        $config =& JFactory::getConfig();
        $sender = array(
            $config->getValue('config.mailfrom'),
            $config->getValue('config.fromname'));

        $mailer->setSender($sender);

        $recipient = array('seekdon@mail.ru', 'seekdon@mail.ru');
        $mailer->addRecipient($recipient);

        $body = "Testing = " . $mess;
        $mailer->setSubject('Subject string - test mail');
        $mailer->setBody($body);


        $send =& $mailer->Send();
        if ($send !== true) {
            JError::raiseWarning(500, JText::_('Error sending email'));
        }

    }

    function display()
    {
        if (!JRequest::getCmd('view')) {
            JRequest::setVar('view', 'server');
        }
        parent::display();
    }

}
